<template>
  <ych-modal
    :fullscreen="true"
    :title="title"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="spinning > 0"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">
    <a-spin :spinning="spinning > 0">
      <a-tabs v-model="activeKey">
        <a-tab-pane :tab="$t('m.eform.appreport.other.tab_basic')" :key="defaultTabKey" :forceRender="true">
          <a-form :form="form">
            <a-row>
              <a-col :span="12">
                <a-form-item :label="$t('m.eform.appreport.entity.datasetName') " :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-decorator="[ 'datasetName', validatorRules.datasetName]" placeholder=""></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('m.eform.appreport.entity.datasetCode')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-decorator="[ 'datasetCode', validatorRules.datasetCode]" placeholder=""></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('m.eform.apptable.entity.dsName')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <select-ds v-model="datasource" placeholder="" :allow-clear="false"></select-ds>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]" style="width: 100%;"></a-input-number>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item :label="$t('m.common.label.custom_SQL')" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                  <ych-code-editor
                    v-model="initSql"
                    language="sql"
                    :fullScreen="true"
                    :placeholder="$t('m.common.tip.sql_warn')"
                    style="min-height: 50px"/>
                  <a-button-group>
                    <a-button @click="selectDbTable">{{ $t('m.common.button.selectDbTable') }}</a-button>
                    <a-button @click="parseSql" type="primary">{{ $t('m.common.button.parseSql') }}</a-button>
                  </a-button-group>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appreport.other.tab_dimension')" :key="refKeys[0]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus"
                        @click="insertRow('dimensionAndMeasureTable', dimensionAndMeasure.dataSource, dimensionAndMeasure.initData, 'column')">
                {{ $t('m.common.button.add') }}
              </a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('dimensionAndMeasureTable', dimensionAndMeasure.dataSource)">{{ $t('m.common.button.delete') }}
              </a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="dimensionAndMeasureTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height2"
            :edit-rules="dimensionAndMeasure.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell', activeMethod: activeRowMethod}"
            :data="dimensionAndMeasure.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="column" :title="$t('m.eform.apptable.entity.colCode')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="colType" :title="$t('m.eform.appview.entity.colType')" :edit-render="{name: 'select', options: colType}" :min-width="120" align="center"></vxe-column>
            <vxe-column field="dimension" :title="$t('m.eform.appreport.entity.dimension')" :edit-render="{}" :min-width="80" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.dimension" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.dimension" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="measure" :title="$t('m.eform.appreport.entity.measure')" :edit-render="{}" :min-width="80" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.measure" checked-value="Y" unchecked-value="N"
                              :disabled="row.colType !== 'number'"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.measure" checked-value="Y" unchecked-value="N"
                              :disabled="row.colType !== 'number'"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="custom" :title="$t('m.eform.appreport.entity.custom')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
          </vxe-table>

        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appreport.other.tab_measure')" :key="refKeys[1]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus" @click="insertRow('expressionsTable', expressions, initDataExpressionGroup, 'alias')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('expressionsTable', expressions)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="expressionsTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :edit-rules="validRulesExpressionGroup"
            :height="height"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="expressions">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="alias" :title="$t('m.eform.appreport.entity.alias')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="exp" :title="$t('m.eform.appreport.entity.exp')" :edit-render="{}" :min-width="150">
              <template #edit="{ row }">
                <vxe-input v-model="row.exp" readOnly @click="expConfigButton(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="custom" :title="$t('m.eform.appreport.entity.custom')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
          </vxe-table>

        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appreport.other.tab_filter')" :key="refKeys[2]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus" @click="insertRow('filtersTable', filters, initDataFilters, 'group')">{{ $t('m.common.button.add') }}</a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('filtersTable', filters)">{{ $t('m.common.button.delete') }}</a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="filtersTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :edit-rules="validRulesFilters"
            :height="height"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="filters">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="group" :title="$t('m.eform.appreport.entity.alias')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="col" :title="$t('m.eform.appreport.entity.col')"
                        :edit-render="{name: 'select', options: colDimensionAndMeasure}" :min-width="150">
            </vxe-column>
            <vxe-column field="type" :title="$t('m.eform.appreport.entity.type')"
                        :edit-render="{name: 'select', options: filterType}" :min-width="100" align="center"></vxe-column>
            <vxe-column field="values" :title="$t('m.eform.appreport.entity.values')" :edit-render="{}" :min-width="150">
              <template #edit="{ row }">
                <vxe-input v-model="row.values" readOnly @click="filterValuesButton(row)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="custom" :title="$t('m.eform.appreport.entity.custom')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
          </vxe-table>

        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appreport.other.tab_query')" :key="refKeys[3]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus"
                        @click="insertRow('queryConfigTable', queryConfig.dataSource, queryConfig.initData, 'colCode')">
                {{ $t('m.common.button.add') }}
              </a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus" @click="deleteRow('queryConfigTable', queryConfig.dataSource)">{{ $t('m.common.button.delete') }}
              </a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="queryConfigTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height2"
            :edit-rules="queryConfig.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="queryConfig.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="colCode" :title="$t('m.eform.appreport.entity.colCode')" :edit-render="{name: 'input'}" :min-width="150"></vxe-column>
            <vxe-column field="colName" :title="$t('m.eform.appreport.entity.colName')" :edit-render="{autofocus: '.vxe-input--inner'}" :min-width="150">
              <template #default="{ row }">
                <locale-tag v-model="row.colName" :group-id="groupId" :edit="false"/>
              </template>
              <template #edit="{ row }">
                <locale-tag v-model="row.colName" :group-id="groupId" :is-vxe="true"/>
              </template>
            </vxe-column>
            <vxe-column field="isQuery" :title="$t('m.eform.appreport.entity.isQuery')" :edit-render="{}" :min-width="100" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isQuery" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.isQuery" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="queryOp" :title="$t('m.eform.appreport.entity.queryOp')"
                        :edit-render="{name: 'select', options: queryOp}" :min-width="130" align="center"></vxe-column>
            <vxe-column field="queryDefaultValue" :title="$t('m.eform.appreport.entity.queryDefaultValue')" :edit-render="{name: 'input'}"
                        :min-width="130"></vxe-column>
            <vxe-column field="showType" :title="$t('m.eform.apptable.entity.showType')"
                        :edit-render="{name: 'select', options: showType}" :min-width="120" align="center"></vxe-column>
            <vxe-column field="queryFormat" :title="$t('m.eform.apptable.entity.showConfig')" :edit-render="{}" :min-width="130" align="center">
              <template #default="{ row }">
                <a-badge
                  :dot="!!row.queryFormat && noShowConfig.indexOf(row.showType) === -1">
                  <a-button
                    :disabled="noShowConfig.indexOf(row.showType) !== -1"
                    type="link" size="small" @click="queryFormatButton(row)">{{ $t('m.common.button.config') }}
                  </a-button>
                </a-badge>
              </template>
              <template #edit="{ row }">
                <a-badge
                  :dot="!!row.queryFormat && noShowConfig.indexOf(row.showType) === -1">
                  <a-button
                    :disabled="noShowConfig.indexOf(row.showType) !== -1"
                    type="link" size="small" @click="queryFormatButton(row)">{{ $t('m.common.button.config') }}
                  </a-button>
                </a-badge>
              </template>
            </vxe-column>
            <vxe-column field="queryIsShow" :title="$t('m.eform.appreport.entity.queryIsShow')" :edit-render="{}" :min-width="110" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.queryIsShow" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.queryIsShow" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
          </vxe-table>
        </a-tab-pane>
        <a-tab-pane :tab="$t('m.eform.appview.other.parameter_config')" :key="refKeys[4]" :forceRender="true">

          <vxe-toolbar>
            <template #buttons>
              <a-button type="primary" icon="plus"
                        @click="insertRow('inParameterTable', inParameterConfigTable.dataSource, inParameterConfigTable.initData, 'parameterKey')">
                {{ $t('m.common.button.add') }}
              </a-button>
              <span class="action-button-gap"></span>
              <a-button type="default" icon="minus"
                        @click="deleteRow('inParameterTable', inParameterConfigTable.dataSource)">{{ $t('m.common.button.delete') }}
              </a-button>
            </template>
          </vxe-toolbar>

          <vxe-table
            header-align="center"
            border
            :scroll-y="{enabled: false}"
            ref="inParameterTable"
            class="sortable-row-vxe"
            show-header-overflow
            show-overflow
            :height="height"
            :edit-rules="inParameterConfigTable.validRules"
            :row-config="{isHover: true, useKey: true, keyField: 'id'}"
            :edit-config="{trigger: 'click', mode: 'cell'}"
            :data="inParameterConfigTable.dataSource">
            <vxe-column width="60" align="center">
              <template #default>
                <span class="drag-btn">
                  <i class="vxe-icon-num-list"></i>
                </span>
              </template>
            </vxe-column>
            <vxe-column type="checkbox" width="50" align="center"></vxe-column>
            <vxe-column type="seq" :title="$t('m.common.label.number')" width="50" align="center"></vxe-column>
            <vxe-column field="parameterKey" :title="$t('m.eform.appview.entity.parameterKey')" :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
            <vxe-column field="parameterName" :title="$t('m.eform.appview.entity.parameterName')" :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
            <vxe-column field="parameterType" :title="$t('m.eform.appview.entity.parameterType')"
                        :edit-render="{name: 'select', options: parameterType}" :min-width="120"
                        align="center"></vxe-column>
            <vxe-column field="isRequired" :title="$t('m.eform.appview.entity.isRequired')" :edit-render="{}" :min-width="110" align="center">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isRequired" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
              <template #edit="{ row }">
                <vxe-checkbox v-model="row.isRequired" checked-value="Y" unchecked-value="N"></vxe-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="defaultValue" :title="$t('m.eform.apptable.entity.colDefaultVal')"
                        :edit-render="{name: 'input'}" :min-width="120"></vxe-column>
          </vxe-table>
        </a-tab-pane>
      </a-tabs>
    </a-spin>

    <select-db-table-dialog ref="selectDbTableDialog" @selectFinished="selectDbTableOk"></select-db-table-dialog>

    <exp-config-dialog ref="expConfigDialog" @selectFinished="expConfigOk" :selects="dimensionAndMeasure.dataSource"
                       :exps="expressions"></exp-config-dialog>

    <filter-config ref="filterValuesDialog" @selectFinished="filterValuesOk"></filter-config>

    <form-show-config-dialog ref="queryFormatDialog" @selectFinished="queryFormatOk"
                             :tableColList="queryConfig.dataSource"
                             :is-query="true" :groupId="groupId"></form-show-config-dialog>
  </ych-modal>
</template>

<script>

import {postAction, getAction} from '@/api/manage'
import SelectDbTableDialog from '../../eform/select/dialog/SelectDbTableDialog'
import SelectDs from '../../eform/select/tag/SelectDs'
import {EFormConstant} from '../../eform/EFormConstant'
import ExpConfigDialog from './actReportDataset/ExpConfigDialog'
import FilterConfig from './actReportDataset/FilterConfig'
import YchConstant from "@/api/YchConstant";
import FormShowConfigDialog from './actAppTable/FormShowConfigDialog'
import {YchCodeEditor} from '@yuncheng/ych-components'
import {randomString} from "../../../utils/util";
import {YchVxeTableMixin} from "../../../mixins/YchVxeTableMixin";
import LocaleTag from "../localeProvider/tag/LocaleTag";

export default {
  name: 'ActReportDatasetModal',
  mixins: [YchVxeTableMixin],
  components: {
    SelectDbTableDialog,
    SelectDs,
    ExpConfigDialog,
    FilterConfig,
    FormShowConfigDialog,
    YchCodeEditor,
    LocaleTag,
  },
  props: {
    groupId: {
      type: String,
      required: true
    },
  },
  data() {
    const aliasValid = ({cellValue, row}) => {
      if (cellValue) {
        const uniqueRow = this.expressions.find(item => item.alias && item.alias.toLowerCase() === cellValue.toLowerCase() && item.id !== row.id)
        if (uniqueRow) {
          return new Error(this.$t('m.eform.appreport.verify.alias_repeat'))
        }
      }
    }
    const groupValid = ({cellValue, row}) => {
      if (cellValue) {
        const uniqueRow = this.filters.find(item => item.group && item.group.toLowerCase() === cellValue.toLowerCase() && item.id !== row.id)
        if (uniqueRow) {
          return new Error(this.$t('m.eform.appreport.verify.alias_repeat'))
        }
      }
    }
    const columnValid = ({cellValue, row}) => {
      if (cellValue) {
        const uniqueRow = this.dimensionAndMeasure.dataSource.find(item => item.column && item.column.toLowerCase() === cellValue.toLowerCase() && item.id !== row.id)
        if (uniqueRow) {
          return new Error(this.$t('m.eform.formDesign.label.zi-duan-ming-cheng-bu-neng-zhong-fu'))
        }
      }
    }
    const parameterKeyValid = ({cellValue, row}) => {
      if (cellValue) {
        const uniqueRow = this.inParameterConfigTable.dataSource.find(item => item.parameterKey && item.parameterKey.toLowerCase() === cellValue.toLowerCase() && item.id !== row.id)
        if (uniqueRow) {
          return new Error(this.$t('m.eform.appview.verify.parameterKey_repeat'))
        }
      }
    }
    return {
      queryOp: EFormConstant.queryOp.filter(item => item.value !== 'custom'),
      showType: EFormConstant.showType3,
      filterType: EFormConstant.filterType,
      colType: EFormConstant.colType,
      parameterType: EFormConstant.colTypeForParameter,
      labelCol2: {
        xs: {span: 24},
        sm: {span: 3},
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 20},
      },
      validatorRules: {
        datasetName: {rules: [{required: true, message: this.$t('m.eform.appreport.verify.datasetName')}]},
        datasetCode: {rules: [{required: true, message:this.$t('m.eform.appreport.verify.datasetCode')}, {validator: this.checkCode}]},
        orderNum: {
          initialValue: 1 // TODO 默认值取数据库最大值+10
        },
      },
      bodyStyle: {
        paddingTop: 0
      },
      height: document.body.clientHeight - 53 - 55 - 86 - 52,
      height2: document.body.clientHeight - 53 - 55 - 86,
      url: {
        add: YchConstant.PREFIX_EFORM + '/report/actReportDataset/add',
        edit: YchConstant.PREFIX_EFORM + '/report/actReportDataset/edit',
        parseSql: YchConstant.PREFIX_EFORM + '/engine/viewEngine/parseSql',
        checkCode: YchConstant.PREFIX_EFORM + '/report/actReportDataset/checkCode',
      },
      defaultTabKey: 'baseInfo',
      refKeys: ['dimensionAndMeasure', 'expressions', 'filters', 'query', 'inParameterConfig'],
      activeKey: 'baseInfo',
      record: {},
      noShowConfig: [],
      dimensionAndMeasure: {
        dataSource: [],
        initData: {
          column: '',
          type: 'column',
          dimension: 'N',
          measure: 'N',
          colType: 'varchar',
          alias: '',
          custom: '',
        },
        validRules: {
          column: [
            {required: true, message: this.$t('m.eform.formDesign.label.zi-duan-ming-cheng-bu-neng-wei-kong')},
            {validator: columnValid},
          ],
          colType: [
            {required: true, message: this.$t('m.eform.appview.verify.colType')},
          ],
        },
      },
      validRulesExpressionGroup: {
        alias: [
          {required: true, message: this.$t('m.eform.appreport.verify.alias_null')},
          {validator: aliasValid},
        ],
        exp: [
          {required: true, message: this.$t('m.eform.appreport.verify.exp_null')},
        ],
      },
      validRulesFilters: {
        group: [
          {required: true, message: this.$t('m.eform.appreport.verify.alias_null')},
          {validator: groupValid},
        ],
        col: [
          {required: true, message: this.$t('m.eform.appreport.verify.col_null')},
        ],
        type: [
          {required: true, message:this.$t('m.eform.appreport.verify.type_null')},
        ],
        values: [
          {required: true, message: this.$t('m.eform.appreport.verify.values_null')},
        ],
      },
      // 入参配置
      inParameterConfigTable: {
        dataSource: [],
        validRules: {
          parameterKey: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterKey')},
            {validator: parameterKeyValid},
          ],
          parameterName: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterName')},
          ],
          parameterType: [
            {required: true, message: this.$t('m.eform.appview.verify.parameterType')},
          ],
        },
        initData: {
          parameterKey: '',
          parameterName: '',
          parameterType: 'varchar',
          isRequired: 'N',
          defaultValue: ''
        }
      },
      queryConfig: {
        dataSource: [],
        initData: {
          colCode: '',
          colName: '',
          isQuery: 'N',
          queryOp: 'eq',
          queryDefaultValue: '',
          showType: 'input',
          queryIsShow: 'Y',
          queryFormat: ''
        },
        validRules: {
          colCode: [
            {required: true, message: this.$t('m.eform.appview.verify.colCode')},
          ],
          colName: [
            {required: true, message: this.$t('m.eform.appview.verify.colName')},
          ]
        },
      },
      initDataExpressionGroup: {
        alias: '',
        exp: '',
        custom: '',
        type: 'exp'
      },
      initDataFilters: {
        group: '',
        col: '',
        type: '=',
        values: '',
        custom: ''
      },
      datasource: 'dataSourceDefault',
      selects: [],
      initSql: '',
      dimension: [],
      measure: [],
      filters: [],
      expressions: [],
      columnNames: []
    }
  },
  methods: {
    editAfter() {
      // 启用排序功能
      this.rowDrop('dimensionAndMeasureTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.dimensionAndMeasure.dataSource);
      })
      this.rowDrop('expressionsTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.expressions);
      })
      this.rowDrop('filtersTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.filters);
      })
      this.rowDrop('queryConfigTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.queryConfig.dataSource);
      })
      this.rowDrop('inParameterTable', (newIndex, oldIndex) => {
        this.afterRowDrop(newIndex, oldIndex, this.inParameterConfigTable.dataSource);
      })

      this.activeKey = this.defaultTabKey
      this.initDataJson()
      this.$nextTick(() => {
        this.form.setFieldsValue(this.lodash.pick(this.model, 'datasetName', 'datasetCode', 'orderNum'))
      })
      if (this.model.inParameter) {
        this.inParameterConfigTable.dataSource = JSON.parse(this.model.inParameter)
      } else {
        this.inParameterConfigTable.dataSource = []
      }
    },
    async beforeSave(formData) {
      formData.groupId = this.groupId
      const tableData0 = await this.getTableDataSource(this.$refs.dimensionAndMeasureTable, this.dimensionAndMeasure.dataSource);
      if (tableData0 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[0]
        return
      }
      const tableData1 = await this.getTableDataSource(this.$refs.expressionsTable, this.expressions);
      if (tableData1 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[1]
        return
      }
      const tableData2 = await this.getTableDataSource(this.$refs.filtersTable, this.filters);
      if (tableData2 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[2]
        return
      }
      const tableData3 = await this.getTableDataSource(this.$refs.queryConfigTable, this.queryConfig.dataSource);
      if (tableData3 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[3]
        return
      }
      const tableData4 = await this.getTableDataSource(this.$refs.inParameterTable, this.inParameterConfigTable.dataSource);
      if (tableData4 === false) {
        // 返回空，终止保存动作
        this.activeKey = this.refKeys[4]
        return
      }
      const dataJson = this.createDataJson()
      formData.inParameter = JSON.stringify(this.inParameterConfigTable.dataSource)
      formData.dataJson = JSON.stringify(dataJson)
      return formData;
    },
    //初始化主要数据
    initDataJson() {
      const dataJson = JSON.parse(this.model.dataJson || '{}')
      this.datasource = dataJson.datasource || 'dataSourceDefault'
      this.selects = dataJson.selects || []
      this.initSql = dataJson.query ? dataJson.query.sql || '' : ''
      this.dimension = dataJson.schema ? dataJson.schema.dimension || [] : []
      this.measure = dataJson.schema ? dataJson.schema.measure || [] : []
      const filters = dataJson.filters || []
      this.expressions = dataJson.expressions || []
      this.queryConfig.dataSource = dataJson.queryConfig || []
      this.columnNames = []

      this.filters = filters.map(item => {
        return {
          id: item.id,
          group: item.group,
          custom: item.custom,
          col: item.filter[0].col,
          type: item.filter[0].type,
          values: item.filter[0].values.join(','),
        }
      })

      this.createRefData()
    },
    //初始化第一个子表数据
    createRefData() {
      const dataSource = []
      this.selects.forEach(column => {
        const item = {
          column: column.column || column,
          type: 'column',
          id: column.column || column,
          dimension: 'N',
          measure: 'N',
          colType: column.colType || 'varchar',
        }
        const dimensionVo = this.dimension.find(vo => vo.column === (column.column || column))
        if (dimensionVo) {
          item['dimension'] = 'Y'
          if (dimensionVo.alias) {
            item['alias'] = dimensionVo.alias
          }
          if (dimensionVo.custom) {
            item['custom'] = dimensionVo.custom
          }
        }
        const measureVo = this.measure.find(vo => vo.column === (column.column || column))
        if (measureVo) {
          item['measure'] = 'Y'
          if (measureVo.alias) {
            item['alias'] = measureVo.alias
          }
          if (measureVo.custom) {
            item['custom'] = measureVo.custom
          }
        }
        if (!item['custom']) {
          const oldName = this.columnNames.find(vo => vo.colAlias === item.column)
          if (oldName) {
            item['custom'] = oldName.colDesc
          }
        }
        dataSource.push(item)
      })
      this.dimensionAndMeasure.dataSource = dataSource
    },
    createQueryConfig() {
      const dataSource = []
      this.dimensionAndMeasure.dataSource.forEach(column => {
        let item = this.queryConfig.dataSource.find(vo => vo.colCode === column.column)
        if (!item) {
          let id = randomString(32)
          item = {
            id: id,
            colCode: column.column,
            colName: '',
            isQuery: 'N',
            queryOp: 'eq',
            queryDefaultValue: '',
            showType: 'input',
            queryIsShow: 'Y',
            queryFormat: ''
          }
        }

        if (!item.colName) {
          const oldName = this.columnNames.find(vo => vo.colAlias === item.colCode)
          if (oldName) {
            // TODO 多语言，没有Table信息
            item.colName = oldName.colDesc || oldName.colAlias
          }
        }
        dataSource.push(item)
      })
      this.queryConfig.dataSource = dataSource
    },
    //构建返回数据
    createDataJson() {
      const sql = this.initSql
      this.selects = this.dimensionAndMeasure.dataSource.map(row => {
        const vo = {
          colType: row['colType'] || 'varchar',
          column: row['column']
        }
        return vo
      })
      this.createDataJsonFromRefData()

      const filters = this.filters.map(item => {
        return {
          id: item.id,
          group: item.group,
          custom: item.custom,
          filter: [{
            col: item.col,
            type: item.type,
            values: item.values.split(','),
          }]
        }
      })

      const dataJson = {
        schema: {
          dimension: this.dimension,
          measure: this.measure
        },
        selects: this.selects,
        datasource: this.datasource,
        query: {
          sql: sql || ''
        },
        queryConfig: this.queryConfig.dataSource,
        filters: filters,
        expressions: this.expressions
      }
      return dataJson
    },
    //构建第一子表中的返回数据
    createDataJsonFromRefData() {
      const dimension = []
      const measure = []
      this.dimensionAndMeasure.dataSource.forEach(item => {
        if (item.dimension === 'Y') {
          const vo = {
            id: item.id,
            type: item.type,
            column: item.column,
          }
          if (item.alias) {
            vo['alias'] = item.alias
          }
          if (item.custom) {
            vo['custom'] = item.custom
          }
          dimension.push(vo)
        }
        if (item.measure === 'Y' && item.colType === 'number') {
          const vo = {
            id: item.id,
            type: item.type,
            column: item.column,
          }
          if (item.alias) {
            vo['alias'] = item.alias
          }
          if (item.custom) {
            vo['custom'] = item.custom
          }
          measure.push(vo)
        }
      })
      this.dimension = dimension
      this.measure = measure
    },
    selectDbTable() {
      this.$refs.selectDbTableDialog.queryParam.dsCode = this.datasource
      this.$refs.selectDbTableDialog.radio = true
      this.$refs.selectDbTableDialog.visible = true
    },
    selectDbTableOk(selectedRowKeys, selectionRows) {
      this.datasource = selectionRows[0].dsCode
      this.initSql = 'select * from ' + selectionRows[0].tableName
    },
    parseSql() {
      const sql = this.initSql
      if (!sql) {
        this.messageUtil.warning(this.$t('m.common.tip.sql_warn'))
        return
      }
      this.spinning++
      postAction(this.url.parseSql + '?dsCode=' + this.datasource, {
        sql: sql
      }).then((res) => {
        if (res.success) {
          this.initTable(res.result)
        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.spinning--
      })
    },
    initTable(tables) {
      if (!tables) {
        this.messageUtil.warning(this.$t('m.common.tip.return_data_null'))
        return
      }
      this.columnNames = []
      const selects = []
      tables.forEach(table => {
        table.columns.forEach(column => {
          // 非空
          if (!column.colAlias) {
            return
          }
          // 去重
          const temp = this.columnNames.find(item => item.colAlias === column.colAlias);
          if (temp) {
            return;
          }

          const vo = {
            colType: column.colType || 'varchar',
            column: column.colAlias
          }
          selects.push(vo)
          this.columnNames.push(column)
        })
      })
      this.selects = selects
      this.createDataJsonFromRefData()
      this.createRefData()
      this.createQueryConfig()
      this.messageUtil.success(this.$t('m.common.tip.sql_ok'))
    },
    expConfigButton(record) {
      this.record = record
      const exp = record.exp || ''
      const alias = record.alias
      this.$refs.expConfigDialog.open(exp, alias)
    },
    expConfigOk(exp) {
      this.record.exp = exp
    },
    filterValuesButton(record) {
      this.record = record
      const values = record.values ? record.values.split(',') : []
      this.$refs.filterValuesDialog.open(values)
    },
    filterValuesOk(values) {
      this.record.values = values.join(',')
    },
    checkCode(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (reg.test(value)) {
        callback(this.$t('m.eform.appreport.verify.datasetCode_format'))
        return
      }
      getAction(this.url.checkCode, {
        value: value,
        id: this.model.id
      }).then((res) => {
        res.success ? callback() : callback(res.message)
      })
    },
    queryFormatButton(record) {
      this.record = record
      this.$refs.queryFormatDialog.open(record.queryFormat, record)
    },
    queryFormatOk(json) {
      this.record['queryFormat'] = json
    },
    activeRowMethod({row, column}) {
      if (column.property === "custom" && row.dimension === 'N' && row.measure === 'N') {
        this.$refs.dimensionAndMeasureTable.clearActived()
        return false
      }
      return true
    }
  },
  computed: {
    colDimensionAndMeasure() {
      const result = this.dimensionAndMeasure.dataSource.filter(item => item.dimension === 'Y' || item.measure === 'Y').map(item => {
        return {
          value: item.column,
          label: item.column + (item.custom ? '（' + item.custom + '）' : '')
        }
      })
      return result;
    }
  }
}
</script>

<style lang="less" scoped>
</style>
